package se.webbzon.boltzmann.camera;

import java.nio.ByteBuffer;

import se.webbzon.oschi01.friendly.Friendly;
import se.webbzon.oschi01.worldeditor.WorldObjectDeflation;
import se.webbzon.oschi01.worldobject.WorldObject;
import se.webbzon.oschi01.worldobject.WorldStaticObject;

public class FixedCameraDeflation extends WorldObjectDeflation {
	
	private static final int hasPlatform = 1;
	private static final int hasTarget = 2;
	
	private byte dependencyMask;

	/*============================================================
	Constructors
	============================================================*/
	
	public FixedCameraDeflation(int deflationProperties, WorldObject[] dependencies) {
		super(deflationProperties, dependencies);
	}
	
	public FixedCameraDeflation(int deflationProperties, FixedCamera camera) {
		super(deflationProperties, extractDependencies(camera));
		if (camera.getPlatform() != null)
			dependencyMask += hasPlatform;
		if (camera.getTarget() != null)
			dependencyMask += hasTarget;
	}
	
	/*============================================================
	Public Methods
	============================================================*/

	@Override public void inflate(ByteBuffer buffer) {
		dependencyMask = buffer.get();
	}

	@Override public ByteBuffer deflate(int allocate) {
		ByteBuffer buff = ByteBuffer.allocate(1);
		buff.put(dependencyMask);
		return buff;
	}
	
	/*============================================================
	Friendly Methods
	============================================================*/
	
	/** Creates a new FixedCamera from this FixedCameraDeflation. **/
	@Friendly FixedCamera makeCamera() {
		WorldStaticObject platform = null;
		WorldStaticObject target = null;
		if (isSet(dependencyMask,hasPlatform)) {
			platform = (WorldStaticObject) getDependency(0);
		} 
		if (isSet(dependencyMask,hasTarget)) {
			target = platform == null ? (WorldStaticObject) getDependency(0) :
										(WorldStaticObject) getDependency(1);
		} 
		return new FixedCamera(platform,target);
	}
	
	/*============================================================
	Private Methods
	============================================================*/
	
	/** Returns true if the given property is set in the given properties. **/
	private static final boolean isSet(int properties, int property) {
		return ((properties & property) == property);
	}
	
	/** Returns an array of the dependencies of the provided fixed camera. **/
	private static final WorldObject[] extractDependencies(FixedCamera camera) {
		WorldStaticObject platform = camera.getPlatform();
		WorldStaticObject target = camera.getTarget();
		if (platform == null) {
			if (target == null)
				return null;
			else
				return new WorldObject[] {target};
		} else if (target == null) {
			return new WorldObject[] {platform};
		} else
			return new WorldObject[] {platform,target};
	}

}
